#include "databasemanager.h"

#include <QDebug>
#include <QStringList>
#include <QSqlError>
#include <QSqlQuery>

DatabaseManager::DatabaseManager(QObject *parent) :
    QObject(parent)
{
    dbPath = "./db.sqlite";
}

void DatabaseManager::openDB()
{
    // using SQLITE driver
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbPath);

    if (db.open()) {
        if (db.tables().indexOf("downloads") == -1) {
            createDownloadsTable();
        }
    } else {
        qCritical() << "Can't create database.";
    }
}

void DatabaseManager::createDownloadsTable() {
    QSqlQuery query(db);
    query.prepare("CREATE TABLE downloads "
                  "(id INTEGER PRIMARY KEY ASC, "
                  " url VARCHAR(512), "
                  " path VARCHAR(512), "
                  " size INTEGER, "
                  " downloaded_size INTEGER, "
                  " priority INTEGER, "
                  " status INTEGER)");
    if (!query.exec())
        qCritical() << query.lastError();
}
